/*********************************************************************
 * Clase de Utilidad: Muestra los FPS empleando una fuente True Type. 
 * Programación Multimedia y Juegos
 * Autor: David Vallejo Fernández    david.vallejo@tegnix.com
 * Autor: Carlos González Morcillo   carlos.gonzalez@tegnix.com
 *
 * You can redistribute and/or modify this file under the terms of the
 * GNU General Public License ad published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * and later version. See <http://www.gnu.org/licenses/>.
 *
 * This file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.  
 *********************************************************************/

package util;

import nme.Lib;
import nme.text.TextField;
import nme.text.TextFormat;
import nme.Assets;

class FpsLabel extends TextField {
  public var _fps:Int;   // Frames por segundo calculados
  var _nFrames:Int;      // Numero de frames transcurridos
  var _firstTime:Int;    // Tiempo desde la ultima vez que se llamo

  // Rangos de tiempo en los que se calculan los FPS de forma efectiva
  static inline var RESETTIME : Int = 2000;
  static inline var MINTIME : Int = 400;

  // Constructor =====================================================
  public function new(XPos:Int=20, YPos:Int=20, col:Int = 0xFFFFFF, 
		      font:String = ""):Void {
    super();
    x = XPos;  y = YPos;  width = 300;  height = 80;
    _nFrames = 0;  _firstTime = Lib.getTimer();

    selectable = false;   // El texto no se puede seleccionar
    embedFonts = true;    // La fuente se incrusta en Flash
    
    if (font == "") font = "_sans";
    else font = Assets.getFont (font).fontName;
    
    var tf:TextFormat = new TextFormat(font, 16, col, true);
    defaultTextFormat = tf;
    htmlText = "FPS: ";
  }

  // update ==========================================================  
  public function update():Void {
    var now = Lib.getTimer();  
    var delta = now - _firstTime;
    _nFrames++;

    if (delta > MINTIME) _fps = Std.int(_nFrames * 1000 / delta);
    htmlText = "FPS (Render): " + _fps;
    if (delta > RESETTIME) {_firstTime = now; _nFrames = 1;}
  }
}